package com.danbay.cloud.account.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.danbay.cloud.account.dto.ContractDto;
import com.danbay.cloud.account.dto.ContractInfoDto;
import com.danbay.cloud.account.entity.Contract;
import com.danbay.cloud.account.mapper.ContractMapper;
import com.danbay.cloud.account.service.api.IContractService;
import com.danbay.framework.exception.BusinessException;
import com.danbay.framework.utils.BeanUtils;
import com.danbay.framework.utils.BeanValidator;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author SJG
 *         2017/12/26.
 */
@Service
@Slf4j
public class ContractService implements IContractService {
    @Autowired
    private ContractMapper contractMapper;

    /**
     * 添加合同号
     * 默认有效期为5年
     *
     * @param contractNum  合同号
     * @param enterpriseId 企业id
     * @return 合同号信息
     */
    public void addContract(String contractNum, Integer enterpriseId) throws BusinessException {
        checkExists(contractNum);
        Contract contract = Contract.builder()
                .num(contractNum)
                .addTime(DateTime.now().toDate())
                .beginTime(DateTime.now().toDate())
                .endTime(DateTime.now().plusYears(5).toDate())
                .enterpriseId(enterpriseId)
                .freeze(false)
                .del(false).build();
        contractMapper.insert(contract);
    }

    /**
     * 检查合同号是否存在
     *
     * @param contractNum 合同号
     * @return 是否存在
     */
    @Override
    public void checkExists(String contractNum) throws BusinessException {
        if( contractMapper.selectById(contractNum) != null){
            throw new BusinessException("合同号已存在");
        }
    }

    /**
     * 添加合同号
     *
     * @param contract 合同号信息
     */
    @Override
    public void add(ContractDto contract) throws BusinessException {
        checkContractTime(contract);
        checkExists(contract.getNum());
        int r = contractMapper.insert(Contract.builder()
                .num(contract.getNum())
                .del(false)
                .freeze(false)
                .enterpriseId(contract.getEnterpriseId())
                .beginTime(contract.getBeginTime())
                .endTime(contract.getEndTime())
                .addTime(DateTime.now().toDate()).build());
        if (r == 0) {
            throw new BusinessException("添加合同失败");
        }
    }

    /**
     * 修改合同信息（有效期）
     *
     * @param contract 合同号信息
     * @throws BusinessException 业务异常
     */
    @Override
    public void edit(ContractDto contract) throws BusinessException {
        checkContractTime(contract);

        int rst = contractMapper.updateById(Contract.builder()
                .num(contract.getNum())
                .beginTime(contract.getBeginTime()).endTime(contract.getEndTime()).build());
        if (rst == 0) {
            throw new BusinessException("修改失败");
        }
    }

    /**
     * 检查合同信息是否正确
     *
     * @param contractDto 合同信息
     * @throws BusinessException 业务异常
     */
    private void checkContractTime(ContractDto contractDto) throws BusinessException {
        BeanValidator.valid(contractDto);
        if (contractDto.getEndTime().getTime() < contractDto.getBeginTime().getTime()) {
            throw new BusinessException("有效期结束时间小于开始时间");
        }
    }

    /**
     * 冻结合同
     *
     * @param num 合同号
     * @throws BusinessException 业务异常
     */
    @Override
    public void freeze(String num) throws BusinessException {
        int r = contractMapper.updateById(Contract.builder().num(num)
                .freeze(true)
                .freezeTime(DateTime.now().toDate()).build());
        if (r == 0) {
            throw new BusinessException("冻结合同失败");
        }
        if (r != 1) {
            log.warn("冻结合同成功，但影响行数为：{}", r);
        }
    }

    /**
     * 解冻合同
     *
     * @param num 合同号
     * @throws BusinessException 业务异常
     */
    @Override
    public void unfreeze(String num) throws BusinessException {
        int r = contractMapper.updateById(Contract.builder().num(num).freeze(false).build());
        if (r == 0) {
            throw new BusinessException("解冻合同失败");
        }
        if (r != 1) {
            log.warn("解冻合同成功，但影响行数为：{}", r);
        }
    }

    /**
     * 删除合同
     *
     * @param num 合同号
     * @throws BusinessException 业务异常
     */
    @Override
    public void delete(String num) throws BusinessException {
        int r = contractMapper.deleteById(num);
        if (r == 0) {
            throw new BusinessException("删除失败");
        }
    }

    /**
     * 删除企业下所有合同
     *
     * @param eid 企业id
     * @throws BusinessException 业务异常
     */
    @Override
    public void deleteByEid(Integer eid) throws BusinessException {
        contractMapper.delete(new EntityWrapper<>(Contract.builder().enterpriseId(eid).build()));
    }

    /**
     * 取企业下所有合同列表
     *
     * @param eid 企业id
     * @return 合同
     */
    @Override
    public List<ContractInfoDto> all(Integer eid) {
        List<Contract> contracts = contractMapper.selectList(new EntityWrapper<>(Contract.builder().enterpriseId(eid).build()));
        return BeanUtils.convert(contracts, ContractInfoDto.class);
    }
}
